package com.heyige.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heyige.common.CommResponse;
import com.heyige.dto.ChatDto;
import com.heyige.dto.request.UpdateTitleRequest;
import com.heyige.entity.AiMessage;
import com.heyige.facade.ChatSessionFacade;
import com.heyige.service.ai.AiModelManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("api/chat")
@Tag(name = "聊天管理", description = "AI聊天相关接口")
public class ChatController {

    private final ChatSessionFacade chatSessionFacade;

    private final AiModelManager aiModelManager;

    /**
     * 创建聊天会话
     */
    @PostMapping("/sessions")
    @Operation(summary = "创建聊天会话", description = "创建一个新的AI聊天会话")
    public CommResponse<ChatDto.SessionResponse> createSession(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "创建会话请求参数") @Valid @RequestBody ChatDto.CreateSessionRequest request) {
        ChatDto.SessionResponse response = chatSessionFacade.createSession(userId, request);
        return CommResponse.ok(response);
    }

    /**
     * 获取用户的会话列表
     */
    @GetMapping("/sessions")
    @Operation(summary = "获取用户会话列表", description = "分页获取用户的聊天会话列表")
    public CommResponse<IPage<ChatDto.SessionResponse>> getUserSessions(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "是否只获取活跃会话", example = "true") @RequestParam(defaultValue = "true") Boolean active,
            @Parameter(description = "页码", example = "0") @RequestParam(defaultValue = "0") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {

        IPage<ChatDto.SessionResponse> sessions = chatSessionFacade.getUserSessions(userId, active, page, size);
        return CommResponse.ok(sessions);
    }

    /**
     * 获取会话详情
     */
    @GetMapping("/sessions/{sessionId}")
    @Operation(summary = "获取会话详情", description = "根据会话ID获取会话详情")
    public CommResponse<ChatDto.SessionResponse> getSession(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "会话ID", required = true, example = "1") @PathVariable Long sessionId) {
        ChatDto.SessionResponse response = chatSessionFacade.getSession(sessionId, userId);
        return CommResponse.ok(response);
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/sessions/{sessionId}")
    @Operation(summary = "删除会话", description = "删除指定的聊天会话")
    public CommResponse<Void> deleteSession(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "会话ID", required = true, example = "1") @PathVariable Long sessionId) {
        chatSessionFacade.deleteSession(sessionId, userId);
        return CommResponse.ok();
    }

    /**
     * 更新会话标题
     */
    @PutMapping("/sessions/{sessionId}/title")
    @Operation(summary = "更新会话标题", description = "更新指定会话的标题")
    public CommResponse<ChatDto.SessionResponse> updateSessionTitle(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "会话ID", required = true, example = "1") @PathVariable Long sessionId,
            @Parameter(description = "更新标题请求参数") @RequestBody UpdateTitleRequest request) {
        ChatDto.SessionResponse response = chatSessionFacade.updateSessionTitle(sessionId, userId, request.getTitle());
        return CommResponse.ok(response);
    }

    /**
     * 发送聊天消息
     */
    @PostMapping("/send")
    @Operation(summary = "发送聊天消息", description = "向AI发送聊天消息并获取回复")
    public CommResponse<ChatDto.ChatResponse> sendMessage(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "聊天请求参数") @Valid @RequestBody ChatDto.ChatRequest request) {
        ChatDto.ChatResponse response = chatSessionFacade.sendMessage(userId, request);
        return CommResponse.ok(response);
    }

    /**
     * 获取会话的聊天历史
     */
    @GetMapping("/sessions/{sessionId}/messages")
    @Operation(summary = "获取聊天历史", description = "获取指定会话的聊天历史记录")
    public CommResponse<List<AiMessage>> getChatHistory(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "会话ID", required = true, example = "1") @PathVariable Long sessionId) {
        List<AiMessage> messages = chatSessionFacade.getChatHistory(sessionId, userId);
        return CommResponse.ok(messages);
    }

    /**
     * 清除会话的聊天历史
     */
    @DeleteMapping("/sessions/{sessionId}/messages")
    @Operation(summary = "清除聊天历史", description = "清除指定会话的聊天历史记录")
    public CommResponse<Void> clearChatHistory(
            @Parameter(hidden = true) @RequestAttribute("userId") Long userId,
            @Parameter(description = "会话ID", required = true, example = "1") @PathVariable Long sessionId) {
        chatSessionFacade.clearChatHistory(sessionId, userId);
        return CommResponse.ok();
    }

    /**
     * 获取所有可用模型
     */
    @GetMapping("/models/available")
    @Operation(summary = "获取可用模型", description = "获取所有可用的AI模型列表")
    public CommResponse<List<String>> getAvailableModels() {
        List<String> models = aiModelManager.getAvailableModels();
        return CommResponse.ok(models);
    }

    /**
     * 检查指定模型是否可用
     */
    @GetMapping("/models/{modelName}/available")
    @Operation(summary = "检查模型可用性", description = "检查指定的AI模型是否可用")
    public CommResponse<Boolean> isModelAvailable(
            @Parameter(description = "模型名称", required = true, example = "deepseek") @PathVariable String modelName) {
        Boolean available = aiModelManager.isModelAvailable(modelName);
        return CommResponse.ok(available);
    }

    /**
     * 获取所有模型状态
     */
    @GetMapping("/models/status")
    @Operation(summary = "获取模型状态", description = "获取所有AI模型的状态信息")
    public CommResponse<List<AiModelManager.ModelStatus>> getModelStatuses() {
        List<AiModelManager.ModelStatus> statuses = aiModelManager.getModelStatuses();
        return CommResponse.ok(statuses);
    }

}